/*
 * Copyright 2010 Assert Developments
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.ad.coffeebreak.web;

import be.ad.coffeebreak.web.exceptions.HttpException;
import be.ad.coffeebreak.web.exceptions.InternalServerException;
import org.apache.log4j.Logger;

import javax.servlet.*;
import java.io.IOException;

/**
 * A filter that will catch http exceptions and transform them into a suitable error page.
 *
 * @author Stefan Bangels
 * @see be.ad.coffeebreak.web.exceptions.HttpException
 */
public class ExceptionFilter implements Filter {

    private final Logger logger = Logger.getLogger(getClass());

    /**
     * Initializes the filter.
     *
     * @param filterConfig the filter configuration
     * @throws ServletException when something terrible has happened
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * Processes the request.
     *
     * @param request     the request
     * @param response    the response
     * @param filterChain the filter chain
     * @throws IOException      when something terrible has happened
     * @throws ServletException when something terrible has happened
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        try {
            try {
                filterChain.doFilter(request, response);
            } catch (HttpException e) {
                throw e;
            } catch (Throwable t) {
                throw new InternalServerException(t);
            }
        } catch (HttpException e) {
            logger.error(e.getMessage(), e);

            // Set error page attributes
            request.setAttribute(WebConstants.ATTRIBUTE_ERROR_EXCEPTION, e);
            request.setAttribute(WebConstants.ATTRIBUTE_ERROR_MESSAGE, e.getMessage());
            request.setAttribute(WebConstants.ATTRIBUTE_ERROR_STATUS_CODE, e.getStatusCode());

            // Dispatch error view
            RequestDispatcher dispatcher = request.getRequestDispatcher(e.getView());
            dispatcher.forward(request, response);
        }
    }

    /**
     * Destroys the filter.
     */
    @Override
    public void destroy() {
    }

}
